package com.conversationboard.controller.blogview;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.conversationboard.cache.ThreadCache;
import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.formatter.DateFormatter;
import com.conversationboard.formatter.ImageHider;
import com.conversationboard.model.Message;
import com.conversationboard.model.Thread;
import com.conversationboard.model.User;

/**
 * Go through the new answers threads and produce a list of blog entries for display
 * 
 * @author Keith Watson
 *
 */

public class BlogDataProducer {

	private static final int NUMBER_OF_THREADS = 50;


	public List<BlogEntry> produceBlogData(User user, boolean isSiteNewAnswers, List<NewAnswersThread> newAnswers) throws SQLException {

		List<BlogEntry> blogEntries = new LinkedList<BlogEntry>();

		int count = 0;

		for (NewAnswersThread newAnswersThread : newAnswers) {

			count++;

			if (count > NUMBER_OF_THREADS) {
				break;
			}

			if (newAnswersThread.isDeleted()) {
				continue;
			}

			Thread thread = ThreadCache.getInstance().get(newAnswersThread.getBoardId(), newAnswersThread.getThreadId());

			if ((thread != null) && user.canRead(thread.getBoardId())) {

				BlogEntry blogEntry = new BlogEntry();

				blogEntry.setThreadName(newAnswersThread.getTitle());
				blogEntry.setLastUpdated(DateFormatter.prettyPrintTime(newAnswersThread.getLastUpdated(), user, false, true));
				blogEntry.setBoardId(newAnswersThread.getBoardId());
				blogEntry.setThreadId(newAnswersThread.getThreadId());
				blogEntry.setLastUpdatedBy(newAnswersThread.getLastUpdatedByDisplayName());

				List<BlogPost> posts = new LinkedList<BlogPost>();

				List<Message> recentMessages = thread.getMessages().getRecentMessages();

				for (Message message : recentMessages) {

					if (message.isDeleted()) {
						continue;
					}

					BlogPost blogPost = new BlogPost();
					blogPost.setDisplayName(message.getDisplayName());
					blogPost.setTimePosted(DateFormatter.prettyPrintTime(message.getTimestamp(), user, false, true));

					String body = ImageHider.substituteImagesForLinks(message.getBody(), user.isAdmin(), false, !user.getPreferences().isShowImages());

					blogPost.setPost(body);
					blogPost.setBoardId(message.getBoardId());
					blogPost.setThreadId(message.getThreadId());
					blogPost.setMessageId(message.getMessageId());
					blogPost.setQuestion(message.isQuestion());

					posts.add(blogPost);
				}

				blogEntry.setPosts(posts);
				blogEntries.add(blogEntry);
			}
		}

		return blogEntries;

	}

}
